//
//  ZSArchiveObjBase.m
//  AllToolsOC
//
//  Created by safiri on 2017/8/8.
//  Copyright © 2017年 safiri. All rights reserved.
//

#import "ZSArchiveObjBase.h"
#import <objc/runtime.h>
#import "ZSFileSerialization.h"

@implementation ZSArchiveObjBase
- (void)encodeWithCoder:(NSCoder *)aCoder{
    //取得对象的所有属性列表
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([self class], &count);
    //循环每个属性，并进行归档处理
    for (int i=0; i < count; i++) {
        Ivar ivar = ivars[i];
        NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
        //kvc取值
        [aCoder encodeObject:[self valueForKey:key] forKey:key];
    }
    free(ivars);
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{

    if (self = [super init]) {
        unsigned int count = 0;
        Ivar * ivars = class_copyIvarList([self class], &count);
        //循环每个属性，并进行解档处理
        for (int i=0; i < count; i++) {
            Ivar ivar = ivars[i];
            NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
            //kvc赋值
            [self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
        }
        free(ivars);
    }
    return self;
}
- (id)copyWithZone:(NSZone *)zone {
    ZSArchiveObjBase *copy = [[[self class] allocWithZone:zone] init];
    return copy;
}

- (BOOL)writeToSandboxDocumentsPathWithFileNameWithFileName:(NSString *)fileName {
    return [NSKeyedArchiver archiveRootObject:self toFile:[ZSArchiveObjBase sandboxDocumentsPathWithFileName:fileName]];
}
- (BOOL)writeToFilePath:(NSString *)filePath {
    return [NSKeyedArchiver archiveRootObject:self toFile:filePath];
}

+ (id)loadFromSandboxDocumentsWithFileName:(NSString *)fileName {
    return [NSKeyedUnarchiver unarchiveObjectWithFile:[ZSArchiveObjBase sandboxDocumentsPathWithFileName:fileName]];
}
+ (id)loadFromFilePath:(NSString *)path {
    return [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}

+ (NSString *)sandboxDocumentsPathWithFileName:(NSString *)fileName {
    NSString *file = [fileName stringByAppendingPathExtension:@"archiver"];
    NSString *filePath = [ZSFileSerialization fileCreatePathInDocumentsWithFileName:file];
    return filePath;
}
@end
